<?php

namespace app\common\model\points_mall;

use addons\xyb\XypHelper;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\Goods as ProductGoods;
use app\common\model\points_mall\Goods as GoodsModel;
use app\common\model\Scenic;
use think\Model;

class Goods extends Model
{
    // 数据库
    protected $name = 'points_mall_goods';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected static $users_exchange_status = [
        'not_logged'  => 0, //未登录
        'exchange'    => 1,//可兑换
        'point_lack'  => 2,//积分不足
        'youth_lack'  => 3,//青年币不足
        'stock_lack'  => 4,//库存不足
        'over_lack'   => 5//超出购买限制
    ];
    // 追加属性
    protected $append = [
        'status_text',
        'create_date'
    ];

    public function getStatusTextAttr($value, $data)
    {
        if (!isset($data['status']) || !$data['status']) {
            return [];
        }
        switch ($data['status']) {
            case '1':
                return ['color' => 'success', 'label' => '销售中'];
                break;
            case '2':
                if (isset($data['listing_time']) && $data['listing_time'] < time()) {
                    return ['color' => 'success', 'label' => '销售中'];
                } else {
                    return ['color' => 'magenta', 'label' => '待上架'];
                }
                break;
            case '3':
                return ['color' => 'orange', 'label' => '仓库中'];
                break;
            case '4':
                return ['color' => 'error', 'label' => '已下架'];
                break;
        }
    }

    public function getCreateDateAttr($value, $data)
    {
        if (isset($data['createtime']) && $data['createtime']) {
            return date('Y-m-d H:i', $data['createtime']);
        } else {
            return '';
        }
    }

    public function getCategoryNameAttr($value, $data)
    {
        if (!isset($data['category_id']) || !$data['category_id']) {
            return '';
        }
        return Category::where('id', $data['category_id'])->value('name');
    }

    public function createGoods($forms){
        $forms['createtime'] = time();
        return $this->create($forms);
    }

    public function updateGoods($goods_id, $forms){
        $forms['updatetime'] = time();
        return $this->where('id', $goods_id)->update($forms);
    }

    public function getGoodsDetails($goods_id)
    {
        $field = 'id,goods_type,reward_coupons_id,name,category_id,cover,introduce,stock,sales_price,market_price,
        payment_type,point_amount,youth_amount,purchase_amount,people_exchange_stated,people_exchange_num,date_exchange_stated,
        date_exchange_days,date_exchange_num,scheduled_off,scheduled_time,listing_time,status,deadline,people_exchange_stated,people_exchange_num,
        date_exchange_stated,date_exchange_days,date_exchange_num,days_exchange_stated,days_exchange_num,days_receive_stated,
        days_receive_start,days_receive_end,packet_amount';
        $goods_details = self::field($field)->where('id', $goods_id)->find();
        if(!$goods_details){
            return [];
        }
        if(isset($goods_details['reward_coupons_id']) && $goods_details['reward_coupons_id']){
            $goods_details['reward_coupons_id'] = XypHelper::formatJsonStringToArray($goods_details['reward_coupons_id']);
        }
        $goods_details['point_amount'] = floatval($goods_details['point_amount']);
        $goods_details['youth_amount'] = floatval($goods_details['youth_amount']);
        $goods_details['purchase_amount'] = floatval($goods_details['purchase_amount']);
        if(isset($goods_details['scheduled_time']) && $goods_details['scheduled_time']){
            $goods_details['scheduled_time'] = date('Y-m-d H:i', $goods_details['scheduled_time']);
        }
        if(isset($goods_details['listing_time']) && $goods_details['listing_time']){
            $goods_details['listing_time'] = date('Y-m-d H:i', $goods_details['listing_time']);
        }
        return $goods_details;
    }

    public static function getAdminLists(){
        $name = request()->param('name', '');
        $goods_type = request()->param('goods_type', '');
        $category_id = request()->param('category_id', '');
        $grant_status = request()->param('status');
        $field = 'id,goods_type,name,category_id,category_id as category_name,cover,sales_price,market_price,status,payment_type,
        point_amount,youth_amount,purchase_amount,people_exchange_stated,people_exchange_num,date_exchange_stated,
        date_exchange_days,date_exchange_num,stock,scheduled_off,scheduled_time,listing_time,sale_num,createtime,
        date_exchange_stated,date_exchange_days,date_exchange_num,days_exchange_stated,days_exchange_num,days_receive_stated,
        days_receive_start,days_receive_end';
        $query = self::field($field)->where('status', '>', 0);
        if ($name) {
            $query->where('name', 'like', "%{$name}%");
        }
        if ($goods_type) {
            $query->where('goods_type', $goods_type);
        }
        if ($category_id) {
            $query->where('category_id', $category_id);
        }
//        if ($deadline_arr = XypHelper::stringToArray($deadline)) {
//            $query->where('start_time','>',  XypHelper::getTimestamp($deadline_arr[0]))
//                ->where('end_time','<',  XypHelper::getTimestamp($deadline_arr[1]));
//        }

        if ($grant_status) {
            $query->where('status', $grant_status);
        }
        return $query->order('id desc')->paginate(10);
    }



    /**
     * 获取商品促销列表
     *
     * 该方法用于根据类别ID和积分范围筛选商品促销列表。它还会对查询结果进行一系列处理，
     * 包括过滤、排序、分页和格式化，以确保返回的数据满足特定的展示需求。
     *
     * @return mixed 商品促销列表
     */
    public static function getGoodsPromotionList($users_id){
        // 获取请求参数：类别ID和积分范围
        $category_id = request()->param('category_id');
        $points = request()->param('points');

        // 定义需要查询的字段
        $field = 'id,goods_type,name,category_id,sales_price,market_price,status,payment_type,point_amount,youth_amount,
        purchase_amount,stock,sale_num,cover,reward_coupons_id,deadline,people_exchange_stated,people_exchange_num,
        date_exchange_stated,date_exchange_days,date_exchange_num,days_exchange_stated,days_exchange_num,days_receive_stated,
        days_receive_start,days_receive_end,introduce,packet_amount';

        // 构建基础查询条件，包括商品状态和上架时间
        $query = self::field($field)->where(function ($query){
            $query->where('status', 1)->whereOr(function ($status_query){
                $status_query->where('status', 2)->where('listing_time','<=', time());
            });
        });

        // 根据类别ID过滤查询结果
        if($category_id){
            $query->where('category_id', $category_id);
        }
        // 根据积分范围过滤查询结果
        if( $points = XypHelper::stringToArrayFilter($points)){
            if(isset($points[0]) && isset($points[1])){
                $query->where(function ($points_query) use ($points){
                    if($points[0]){
                        $points_query->where('point_amount', '>=', $points[0]);
                    }
                    if($points[1]){
                        $points_query->where('point_amount', '<=', $points[1]);
                    }
                });
            }
        }
        // 执行查询，按ID降序排序，并分页显示，每页10条记录
        $lists = $query->order('id desc')->paginate(10);

        // 如果查询结果为空，直接返回空列表
        if(!$lists->count()){
            return $lists;
        }
        // 遍历查询结果，处理每个商品的信息
        foreach ($lists as $key => $value){
            // 为商品封面图片添加CDN链接
            $lists[$key]['cover'] = cdnurl($value['cover']);
            if($value['reward_coupons_id']){
                // 获取商品关联的优惠券信息
                $lists[$key]['reward_coupons_id'] = MarketingCoupons::getAssociationCouponsArray($value['reward_coupons_id']);
            }
            // 将价格和数量等字段转换为浮点数格式
            $lists[$key]['goods_type'] = floatval($value['goods_type']);
            $lists[$key]['sales_price'] = floatval($value['sales_price']);
            $lists[$key]['market_price'] = floatval($value['market_price']);
            $lists[$key]['payment_type'] = floatval($value['payment_type']);
            $lists[$key]['point_amount'] = floatval($value['point_amount']);
            $lists[$key]['youth_amount'] = floatval($value['youth_amount']);
            $lists[$key]['purchase_amount'] = floatval($value['purchase_amount']);
            $lists[$key]['packet_amount'] = floatval($value['packet_amount']);
            $lists[$key]['stock'] = floatval($value['stock']);
            $lists[$key]['sale_num'] = floatval($value['sale_num']);
            $lists[$key]['exchange_status'] = GoodsModel::getUsersExchangeStatus($value, $users_id);
            if($value['goods_type'] == 2){
                $lists[$key]['introduce'] = floatval($value['packet_amount']).'元红包，兑换后可提现到余额';
            }
            // 初始化商品状态为正常
            $lists[$key]['status'] = 1;
            // 如果商品库存小于0，设置商品状态为缺货
            if($value['stock'] < 0){
                $lists[$key]['status'] = 2;
            }
        }
        // 返回处理后的商品促销列表
        return $lists;
    }

    public static function getGoodsPreviewDetails($goods_id){
        // 定义需要查询的字段
        $field = 'id,goods_type,name,category_id,sales_price,market_price,status,payment_type,point_amount,youth_amount,
        purchase_amount,stock,sale_num,cover,reward_coupons_id,describe,people_exchange_stated,people_exchange_num,
        date_exchange_stated,date_exchange_days,date_exchange_num,days_exchange_stated,days_exchange_num,days_receive_stated,
        days_receive_start,days_receive_end,introduce,packet_amount';

        // 构建基础查询条件，包括商品状态和上架时间
        $details = self::field($field)->where('id', $goods_id)->where(function ($query){
            $query->where('status', 1)->whereOr(function ($status_query){
                $status_query->where('status', 2)->where('listing_time','<=', time());
            });
        })->find();
        if(!$details){
            return false;
        }
        $details['carousel'] = [cdnurl($details['cover'])];
        if($details['reward_coupons_id']){
            $details['reward_coupons_id'] = self::merchantsObtainDiscountCoupons($details['reward_coupons_id']);
        }
        $details['goods_type'] = floatval($details['goods_type']);
        $details['sales_price'] = floatval($details['sales_price']);
        $details['market_price'] = floatval($details['market_price']);
        $details['payment_type'] = floatval($details['payment_type']);
        $details['point_amount'] = floatval($details['point_amount']);
        $details['youth_amount'] = floatval($details['youth_amount']);
        $details['purchase_amount'] = floatval($details['purchase_amount']);
        $details['packet_amount'] = floatval($details['packet_amount']);
        $details['stock'] = floatval($details['stock']);
        $details['sale_num'] = floatval($details['sale_num']);
        $details['provider'] = isset($details['reward_coupons_id']['provider'])?$details['reward_coupons_id']['provider']:[];
        $details['exchange_rules'] = isset($details['reward_coupons_id']['exchange_rules'])?$details['reward_coupons_id']['exchange_rules']:[];
        $details['payment_method'] = '';
        if (in_array($details['payment_type'], [1, 3])){
            $details['payment_method'] = $details['point_amount'].'积分';
        }
        if (in_array($details['payment_type'], [2, 4])){
            $details['payment_method'] = $details['youth_amount'].'青年币';
        }
        if (in_array($details['payment_type'], [3, 4, 5])){
            $details['payment_method'] = ($details['payment_method']?'+':'').$details['purchase_amount'].'元';
        }
        if($details['goods_type'] == 2){
            $details['introduce'] = floatval($details['packet_amount']).'元红包，兑换后可提现到余额';;
        }
        $details['payment_method'].='可兑换';
        // 初始化商品状态为正常
        $details['status'] = 1;
        // 如果商品库存小于0，设置商品状态为缺货
        if($details['stock'] < 0){
            $details['status'] = 2;
        }
        return $details;
    }

    public static function getGoodsPaymentDetails($goods_id){
        // 定义需要查询的字段
        $field = 'id,goods_type,name,category_id,sales_price,market_price,status,payment_type,point_amount,youth_amount,
        purchase_amount,stock,sale_num,cover,reward_coupons_id,describe,people_exchange_stated,people_exchange_num,
        date_exchange_stated,date_exchange_days,date_exchange_num,deadline,introduce,packet_amount';

        // 构建基础查询条件，包括商品状态和上架时间
        $details = self::field($field)->where('id', $goods_id)->where('stock', '>', 0)->where(function ($query){
            $query->where('status', 1)->whereOr(function ($status_query){
                $status_query->where('status', 2)->where('listing_time','<=', time());
            });
        })->where(function ($query){
            $query->where('scheduled_off', 2)->whereOr(function ($status_query){
                $status_query->where('scheduled_off', 1)->where('scheduled_time','>', (time()+120));
            });
        })->find();
        if(!$details){
            return false;
        }
        $details['carousel'] = [cdnurl($details['cover'])];
        if($details['reward_coupons_id']){
            $details['reward_coupons_id'] = self::merchantsObtainDiscountCoupons($details['reward_coupons_id']);
        }
        $details['goods_type'] = floatval($details['goods_type']);
        $details['sales_price'] = floatval($details['sales_price']);
        $details['market_price'] = floatval($details['market_price']);
        $details['payment_type'] = floatval($details['payment_type']);
        $details['point_amount'] = floatval($details['point_amount']);
        $details['youth_amount'] = floatval($details['youth_amount']);
        $details['purchase_amount'] = floatval($details['purchase_amount']);
        $details['packet_amount'] = floatval($details['packet_amount']);
        if($details['goods_type'] == 2){
            $details['introduce'] = floatval($details['packet_amount']).'元红包，兑换后可提现到余额';
        }
        return $details;
    }

    public static function getGoodsRecommend($goods_id, $users_id){
        // 定义需要查询的字段
        $field = 'id,goods_type,name,category_id,sales_price,market_price,status,payment_type,point_amount,youth_amount,
        purchase_amount,stock,sale_num,cover,reward_coupons_id,stock,people_exchange_stated,people_exchange_num,
        date_exchange_stated,date_exchange_days,date_exchange_num,days_exchange_stated,days_exchange_num,days_receive_stated,
        days_receive_start,days_receive_end,introduce,packet_amount';

        // 构建基础查询条件，包括商品状态和上架时间
        $query = self::field($field)->where('id', 'neq', $goods_id)->where(function ($query){
            $query->where('status', 1)->whereOr(function ($status_query){
                $status_query->where('status', 2)->where('listing_time','<=', time());
            });
        })->where('stock', '>', 0);

        // 执行查询，按ID降序排序，并分页显示，每页10条记录
        $lists = $query->order('sale_num desc')->order('id desc')->limit(10)->select();

        // 如果查询结果为空，直接返回空列表
        if(!$lists){
            return [];
        }
        // 遍历查询结果，处理每个商品的信息
        foreach ($lists as $key => $value){
            // 为商品封面图片添加CDN链接
            $lists[$key]['cover'] = cdnurl($value['cover']);
            if($value['reward_coupons_id']){
                // 获取商品关联的优惠券信息
                $lists[$key]['reward_coupons_id'] = MarketingCoupons::getAssociationCouponsArray($value['reward_coupons_id']);
            }
            // 将价格和数量等字段转换为浮点数格式
            $lists[$key]['goods_type'] = floatval($value['goods_type']);
            $lists[$key]['sales_price'] = floatval($value['sales_price']);
            $lists[$key]['market_price'] = floatval($value['market_price']);
            $lists[$key]['payment_type'] = floatval($value['payment_type']);
            $lists[$key]['point_amount'] = floatval($value['point_amount']);
            $lists[$key]['youth_amount'] = floatval($value['youth_amount']);
            $lists[$key]['purchase_amount'] = floatval($value['purchase_amount']);
            $lists[$key]['stock'] = floatval($value['stock']);
            $lists[$key]['sale_num'] = floatval($value['sale_num']);
            $lists[$key]['exchange_status'] = GoodsModel::getUsersExchangeStatus($value, $users_id);
            if($value['goods_type'] == 2){
                $lists[$key]['introduce'] = floatval($value['packet_amount']).'元红包，兑换后可提现到余额';
            }
            // 初始化商品状态为正常
            $lists[$key]['status'] = 1;
            // 如果商品库存小于0，设置商品状态为缺货
            if($lists[$key]['stock'] < 0){
                $lists[$key]['status'] = 2;
            }
        }
        // 返回处理后的商品促销列表
        return $lists;
    }

    public static function merchantsObtainDiscountCoupons($reward_coupons_id){
        if(!$coupons = MarketingCoupons::getAssociationCouponsArray($reward_coupons_id)){
            return false;
        }
        if(isset($coupons[0]) && ($coupons[0])){
            $coupons = $coupons[0];
        }
        $provider = ['id' => 0, 'label' => '官方提供', 'picture' => '', 'type' => 1];
        if($coupons['grant_ticket_method'] == 2){
            $provider = ['id' => 0, 'label' => '多个商家提供', 'picture' => '', 'type' => 2];
        }
        $product_id = XypHelper::stringToArray($coupons['grant_ticket_product_id']);
        if($coupons['grant_ticket_method'] == 3 && $product_id){
            if($scenic_id = ProductGoods::where('id', $product_id[0])->value('scenic_id')){
                $provider = Scenic::field('id,scenic_name as name ,scenic_images as picture')->where('id',$scenic_id)->find();
            }
            if($provider && ($provider['picture'])){
                if($scenic_images = XypHelper::stringToArray($provider['picture'])){
                    $provider['picture'] = cdnurl($scenic_images[0]);
                }
                $provider['type'] = 3;
            }
        }
        $coupons['provider'] = $provider;
        $coupons['exchange_rules'] = '兑换后'.((int)($coupons['effective_days'] / 24)).'天有效，未使用过期前可申请退还';
        unset($coupons['receive_time'],$coupons['use_time'],$coupons['deadline_stated_text'],$coupons['receive_stated']);
        $coupons['use_system_product'] = MarketingCoupons::usingSystemProducts($coupons);
        return $coupons;
    }

    public static function getUsersExchangeStatus($details, $users_id){

       if(isset($details['stock'])){
           if(!$details['stock']){
               return ['status' => self::$users_exchange_status['stock_lack'], 'text' => '库存不足'];
           }
       }
        if(!$users_id){
            return ['status' => self::$users_exchange_status['not_logged'], 'text' => '登录后可兑换'];
        }
        $field = 'id,score as point_amount,youth_coin as youth_amount';
        if(!$users = \app\admin\model\User::field($field)->where('id', $users_id)->find()){
            return ['status' => self::$users_exchange_status['not_logged'], 'text' => '登录后可兑换'];
        }
        /*限制用户的兑换次数*/
        if(isset($details['people_exchange_stated']) && $details['people_exchange_stated'] == 1){
            $users_exchange_number = Orders::getUsersExchangeNumber($users_id, $details['id']);
            $people_exchange_num = (int)(isset($details['people_exchange_num']) && $details['people_exchange_num']?$details['people_exchange_num']:0);
            if($users_exchange_number > $people_exchange_num){
                return ['status' => self::$users_exchange_status['over_lack'], 'text' => '您暂时没有该商品的兑换资格，请选择其他商品'];
            }
        }
        /*周期兑换限制*/
        if(isset($details['people_exchange_stated']) && $details['people_exchange_stated'] == 1){
            $date_exchange_days = (int)(isset($details['date_exchange_days']) && $details['date_exchange_days']?$details['date_exchange_days']:0);
            $date_exchange_time = (time() - ($date_exchange_days * 86400));
            $users_exchange_recently_date = Orders::getUsersSpecifyDateExchangeNumber($users_id, $details['id'], $date_exchange_time);
            $date_exchange_num = (int)(isset($details['date_exchange_num']) && $details['date_exchange_num']?$details['date_exchange_num']:0);
            if($users_exchange_recently_date >= $date_exchange_num){
                return ['status' => self::$users_exchange_status['over_lack'], 'text' => $date_exchange_days.'天内最多可兑换'.$date_exchange_num.'次'];
            }
        }

        /*每天领取限制*/
        if(isset($details['days_receive_stated']) && $details['days_receive_stated'] == 1){
            $time = time();
            if($days_receive_start = (isset($details['days_receive_start']) && $details['days_receive_start']?$details['days_receive_start']:'')){
                $days_receive_start = strtotime(date('Y-m-d '.$details['days_receive_start']));
                if($days_receive_start > $time){
                    return ['status' => self::$users_exchange_status['over_lack'], 'text' => date('H:i',$days_receive_start ).'后可兑换'];
                }
            }
            if($days_receive_start = (isset($details['days_receive_end']) && $details['days_receive_end']?$details['days_receive_end']:'')){
                $days_receive_end = strtotime(date('Y-m-d '.$details['days_receive_end']));
                if($time > $days_receive_end){
                    return ['status' => self::$users_exchange_status['over_lack'], 'text' => '兑换已结束，明天再来吧'];
                }
            }
        }

        /*每日发放数量*/
        if(isset($details['days_exchange_stated']) && $details['days_exchange_stated'] == 1){
            $days_exchange_num = (int)(isset($details['days_exchange_num']) && $details['days_exchange_num']?$details['days_exchange_num']:0);
            $goods_exchange_number = Orders::getGoodsTodaysExchangeNumber($details['id']);
            if($goods_exchange_number >= $days_exchange_num){
                return ['status' => self::$users_exchange_status['over_lack'], 'text' => '兑换已结束，明天再来吧'];
            }
        }

        /*支付类型限制*/
        if($payment_type = (isset($details['payment_type'])?$details['payment_type']:0)){
            $point_amount = (int)(isset($details['point_amount']) && $details['point_amount']?$details['point_amount']:0);
            $youth_amount = (int)(isset($details['youth_amount']) && $details['youth_amount']?$details['youth_amount']:0);
            if(in_array($payment_type, [1, 3])){
                if($point_amount > $details->point_amount){
                    return ['status' => self::$users_exchange_status['point_lack'], 'text' => '积分不足'];
                }
            }
            if(in_array($payment_type, [2, 4])){
                if($youth_amount > $details->youth_amount){
                    return ['status' => self::$users_exchange_status['youth_lack'], 'text' => '青年币不足'];
                }
            }
        }
       return ['status' => self::$users_exchange_status['exchange'], 'text' => '立即兑换'];
    }
}
